package com.daniel.dianping.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.daniel.dianping.dto.Result;
import com.daniel.dianping.entity.ShopType;
import com.daniel.dianping.mapper.ShopTypeMapper;
import com.daniel.dianping.service.IShopTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.daniel.dianping.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author daniel
 * @since 2022-06-29
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    
    @Override
    public Result queryTypeList() {
        // 查询缓存
        String shopTypeStrCache = stringRedisTemplate.opsForValue().get(CACHE_SHOP_TYPE_KEY);
        if (StrUtil.isNotBlank(shopTypeStrCache)) {
            // 不为空返回
            JSONArray jsonArray = JSONUtil.parseArray(shopTypeStrCache);
            List<ShopType> typeList = JSONUtil.toList(jsonArray, ShopType.class);
            return Result.ok(typeList);
        }
        // 未命中，查询数据库
        List<ShopType> typeList = query().orderByAsc("sort").list();
        if (typeList.size() == 0) {
            return Result.fail("商户类型为空");
        }
        // 保存到redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_TYPE_KEY, JSONUtil.toJsonStr(typeList));
        // 返回数据
        return Result.ok(typeList);
    }
}
